/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.store;

import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.logging.InternalLoggerFactory;
import org.apache.rocketmq.store.config.MessageStoreConfig;
import org.apache.rocketmq.store.util.LibC;
import sun.nio.ch.DirectBuffer;

public class TransientStorePool {
    private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);

    //池的大小
    private final int poolSize;
    //文件大小
    private final int fileSize;
    //Deque特性：既具有FIFO特点又具有LIFO特点，即是队列又是栈
    //拥有一组堆内内存
    private final Deque<ByteBuffer> availableBuffers;
    private final MessageStoreConfig storeConfig;

    public TransientStorePool(final MessageStoreConfig storeConfig) {
        this.storeConfig = storeConfig;
        //5
        this.poolSize = storeConfig.getTransientStorePoolSize();
        //1G
        this.fileSize = storeConfig.getMappedFileSizeCommitLog();
        this.availableBuffers = new ConcurrentLinkedDeque<>();
    }

    /**
     * It's a heavy init method.
     */
    public void init() {
        for (int i = 0; i < poolSize; i++) {
            //分配了5个1G大小的堆外内存缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize);

            //DirectBuffer这个东西很容易讲，一句话就能说清楚：这是一块在Java堆外分配的，可以在Java程序中访问的内存。

           // 提供内存锁定功能，即这部分内存不会被置换,意思就是当内存不足的时候，改内存数据不会被置换到磁盘上
            final long address = ((DirectBuffer) byteBuffer).address();
            Pointer pointer = new Pointer(address);
            //锁住这块filesize大小的内存地址
            LibC.INSTANCE.mlock(pointer, new NativeLong(fileSize));
            //把这个堆外内存添加到Deque集合中
            availableBuffers.offer(byteBuffer);
        }
    }

    public void destroy() {
        for (ByteBuffer byteBuffer : availableBuffers) {
            final long address = ((DirectBuffer) byteBuffer).address();
            Pointer pointer = new Pointer(address);
            //释放这个内存地址
            LibC.INSTANCE.munlock(pointer, new NativeLong(fileSize));
        }
    }

    /**
     * 在消息写入消息时，首先从池子中获取一个DirectByteBuffer进行消息的追加。
     * 当5个DirectByteBuffer全部写满消息后，该如何处理呢？从RocketMQ的设计中来看，
     * 同一时间，只会对一个commitlog文件进行顺序写，写完一个后，
     * 继续创建一个新的commitlog文件。
     * 故TransientStorePool的设计思想是循环利用这5个DirectByteBuffer，
     * 只需要写入到DirectByteBuffer的内容被提交到PageCache后，即可重复利用。对应的代码如下：
     */
    public void returnBuffer(ByteBuffer byteBuffer) {
        byteBuffer.position(0);
        byteBuffer.limit(fileSize);
        //传一个buffer进去，给你1G的大小，并添加到buffer集合中第一个元素的位置
        this.availableBuffers.offerFirst(byteBuffer);
    }

    public ByteBuffer borrowBuffer() {
        //从缓冲集合中拿出第一个buffer对象
        ByteBuffer buffer = availableBuffers.pollFirst();
        //poolSize * 0.4=2
        //availableBuffers.size()初始化的时候是5个。
        //意思就是availableBuffers装的不到2个buffer的适时候
        if (availableBuffers.size() < poolSize * 0.4) {
            log.warn("TransientStorePool only remain {} sheets.", availableBuffers.size());
        }
        return buffer;
    }

    public int availableBufferNums() {
        if (storeConfig.isTransientStorePoolEnable()) {
            return availableBuffers.size();
        }
        return Integer.MAX_VALUE;
    }
}
